import React, { Component } from 'react'
import {
  Text,
  View,
  Image,
  StyleSheet,
  ScrollView,
  StatusBar,
  Dimensions,
  Platform,
  PixelRatio,
  AlertIOS,
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
  TouchableWithoutFeedback,
  RefreshControl,
  DeviceEventEmitter,
} from 'react-native'
import Immutable from 'immutable'
import Icon from 'react-native-vector-icons/Ionicons'
import QRCode from 'react-native-qrcode'
import Item from '../component/Item'
import RootView from '../component/RootView'
import Base from './Base'
import { NavigationActions, px2dp, createAction } from '../utils'
import * as userService from '../services/user'
import LocalImg from '../images'

const { width, height } = Dimensions.get('window')

const borderWidth = (Platform.OS === 'ios' ? 1.0 : 1.0) / PixelRatio.get()

class Account extends Base {
  constructor(props) {
    super(props)
    this.state = {
      fetching: false,
      msg: null,
      userInfo: Immutable.Map(),
    }
    this.config = [
      {
        icon: 'ios-pin',
        name: '地址管理',
        first: true,
        onPress: () => {
          this.skipTo('Address', { selectable: 0 })
        },
      },
      {
        icon: 'ios-heart',
        name: '意见反馈',
        first: true,
        color: '#fc7b53',
        onPress: () => {
          this.skipTo('Suggestion')
        },
      },
      {
        icon: 'ios-help-circle',
        name: '关于我们',
        onPress: () => {
          this.goto('About')
        },
      },
    ]
    this.subscription = null
    this.navListener = null
  }
  static navigationOptions = {
    title: '我的',
    headerBackTitle: null,
    headerTitleStyle: {
      color: 'white',
      alignSelf: 'center',
    },
    headerStyle: {
      backgroundColor: '#0398ff',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 0,
    },
    tabBarLabel: '我的',
    tabBarIcon: ({ focused, tintColor }) => {
      if (focused) {
        return <Icon name="ios-person" style={{ color: tintColor }} size={30} />
      }
      return (
        <Icon name="ios-person-outline" style={{ color: 'gray' }} size={30} />
      )
    },
  }
  async avatar(mobile){
    this.goto('Avatar',{key:mobile})
    return
    await this.checkLogin()
    if (!this.state.userInfo) {
      this.goto('Login')
      return
    }
    
  }
  async profile() {
    await this.checkLogin()
    if (!this.state.userInfo) {
      this.goto('Login')
      return
    }
    this.goto('Setting')
  }
  async skipTo(screenName, params) {
    await this.checkLogin()
    if (!this.state.userInfo) {
      this.goto('Login')
      return
    }
    this.goto(screenName, params)
  }
  componentWillUnmount() {
    this.subscription.remove()
    this.navListener.remove()
  }
  onEvent() {
    this.onRefresh()
  }

  onRefresh() {
    this.setState({ fetching: true })

    userService
      .info()
      .then(data => {
        if (!data.user) {
          this.setState({ fetching: false, userInfo: null })
          return
        }
        this.setState({
          fetching: false,
          userInfo: Immutable.fromJS(data.user),
        })
      })
      .catch(e => {
        this.setState({ fetching: false, userInfo: null })
      })
  }
  renderListItem() {
    return this.config.map((item, i) => <Item key={i} {...item} />)
  }
  componentDidMount() {
    this.onRefresh()
    this.subscription = DeviceEventEmitter.addListener(
      'account.reload',
      this.onEvent.bind(this)
    )
    this.navListener = this.props.navigation.addListener('didFocus', () => {
      StatusBar.setBarStyle('light-content')
      // isAndroid && StatusBar.setBackgroundColor('#6a51ae');
    })
  }
  render() {
    const { fetching, userInfo, msg } = this.state
    return (
      <RootView fetching={fetching} style={styles.container} nobar>
        <ScrollView
          style={styles.scrollView}
          refreshControl={
            <RefreshControl
              refreshing={!!fetching}
              onRefresh={this.onRefresh.bind(this)}
              tintColor="#fff"
              colors={['#ddd', '#0398ff']}
              progressBackgroundColor="#ffffff"
            />
          }
        >
          <View
            style={{
              flex: 1,
              backgroundColor: '#f3f3f3',
            }}
          >
            
              <View style={styles.userHead}>
                <View style={{ flex: 1, flexDirection: 'row' }}>
                {userInfo ?
                  <TouchableWithoutFeedback onPress={() => this.avatar(userInfo.get('mobile'))}>
                   <View>
                    <QRCode
                    value={userInfo.get('mobile')}
                    size={48}
                    bgColor='black'
                    fgColor='white'/>
                    </View>
                  </TouchableWithoutFeedback>:
                  <Image
                    source={LocalImg.avatar}
                    style={{
                      width: px2dp(48),
                      height: px2dp(48),
                      borderRadius: px2dp(24),
                    }}
                    />
                }
                  <TouchableWithoutFeedback onPress={() => this.profile()}>
                  <View
                    style={{
                      flex: 1,
                      marginLeft: 10,
                      paddingVertical: 5,
                      justifyContent: 'center',
                    }}
                  >
                    {/**
                    <Text style={{color: "#fff", fontSize: px2dp(16)}}>匿名用户</Text>
                    * */}
                    <View style={{ marginTop: 0, flexDirection: 'row' }}>
                      <Text style={{ color: '#fff' }}>
                        {userInfo ? userInfo.get('mobile') : '请登录'}
                      </Text>
                    </View>
                  </View>
                  </TouchableWithoutFeedback>
                </View>
                <Icon
                  name="ios-arrow-forward-outline"
                  size={px2dp(22)}
                  color="#fff"
                />
              </View>
            
            <View style={styles.numbers}>
              <TouchableWithoutFeedback
                onPress={() => this.skipTo('OrderList', { type: 2 })}
              >
                <View style={styles.numItem}>
                  <Icon
                    name="ios-card-outline"
                    size={20}
                    style={{ color: '#333' }}
                  />
                  <Text
                    style={{
                      color: '#333',
                      fontSize: 12,
                      textAlign: 'center',
                      paddingTop: 5,
                    }}
                  >
                    {'待付款'}
                  </Text>
                </View>
              </TouchableWithoutFeedback>
              <TouchableWithoutFeedback
                onPress={() => this.skipTo('OrderList', { type: 3 })}
              >
                <View style={styles.numItem}>
                  <Icon
                    name="ios-plane-outline"
                    size={20}
                    style={{ color: '#333' }}
                  />
                  <Text
                    style={{
                      color: '#333',
                      fontSize: 12,
                      textAlign: 'center',
                      paddingTop: 5,
                    }}
                  >
                    {'配送中'}
                  </Text>
                </View>
              </TouchableWithoutFeedback>
              <TouchableWithoutFeedback
                onPress={() => this.skipTo('OrderList', { type: 4 })}
              >
                <View style={[styles.numItem]}>
                  <Icon
                    name="ios-trophy-outline"
                    size={20}
                    style={{ color: '#333' }}
                  />
                  <Text
                    style={{
                      color: '#333',
                      fontSize: 12,
                      textAlign: 'center',
                      paddingTop: 5,
                    }}
                  >
                    {'已完成'}
                  </Text>
                </View>
              </TouchableWithoutFeedback>
              <TouchableWithoutFeedback
                onPress={() => this.skipTo('OrderList', { type: 5 })}
              >
                <View style={styles.numItem}>
                  <Icon
                    name="ios-trash-outline"
                    size={20}
                    style={{ color: '#333' }}
                  />
                  <Text
                    style={{
                      color: '#333',
                      fontSize: 12,
                      textAlign: 'center',
                      paddingTop: 5,
                    }}
                  >
                    {'已取消'}
                  </Text>
                </View>
              </TouchableWithoutFeedback>
              <TouchableWithoutFeedback
                onPress={() => this.skipTo('OrderList', { type: 1 })}
              >
                <View
                  style={[
                    styles.numItem,
                    {
                      borderLeftWidth: borderWidth,
                      borderLeftColor: '#f5f5f5',
                    },
                  ]}
                >
                  <Icon
                    name="ios-paper-outline"
                    size={20}
                    style={{ color: '#333' }}
                  />
                  <Text
                    style={{
                      color: '#333',
                      fontSize: 12,
                      textAlign: 'center',
                      paddingTop: 5,
                    }}
                  >
                    {'我的订单'}
                  </Text>
                </View>
              </TouchableWithoutFeedback>
            </View>
            <View>{this.renderListItem()}</View>
          </View>
        </ScrollView>
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {},
  userHead: {
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    paddingHorizontal: 20,
    paddingVertical: 20,
    backgroundColor: '#0398ff',
    // backgroundColor: '#0398ff',
  },
  numbers: {
    flexDirection: 'row',
    backgroundColor: '#fff',
    height: 74,
  },
  numItem: {
    flex: 1,
    height: 74,
    justifyContent: 'center',
    alignItems: 'center',
  },
})

export default Account
